package com.hua.ui;

import javax.swing.UIManager;

import javax.swing.border.EmptyBorder;

import org.omg.CORBA.PUBLIC_MEMBER;

import javax.swing.JFrame;
import com.formdev.flatlaf.FlatLightLaf;
import com.hua.Dao.SqlService;
import com.hua.Model.FileInfo;
import com.hua.Model.PermissInfo;
import com.hua.Model.UploadInfo;
import com.hua.Model.UserInfo;
import com.hua.Service.funtion;
import com.hua.Service.query;
import com.hua.Service.upload_download;

import javax.swing.JPanel;
import javax.swing.JPopupMenu;

import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JMenuItem;

import java.awt.CardLayout;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Panel;
import java.awt.ScrollPane;
import java.awt.Color;
import java.awt.SystemColor;
import java.awt.Window;
import java.lang.invoke.SwitchPoint;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;

import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import java.awt.Button;
import javax.swing.JButton;
import javax.swing.JFileChooser;

import java.awt.event.*;
import java.io.IOException;
import javax.imageio.ImageIO;

import java.net.MalformedURLException;
import java.net.URL;
import java.awt.image.BufferedImage;

public class main extends JFrame {
	private int width = 70, height = 70;
	private int list_width = 40, list_height = 40;
	private ImageIcon image;
	private JTextField textField;
	public static List<UploadInfo> files_upload = new ArrayList<>();
	public static List<FileInfo> files = new ArrayList<>();
	CardLayout cardLayout = new CardLayout();
	SqlService service = new SqlService();
	static {
		// 先设置外观，再创建UI。
		// 为了保证创建UI时，已经实现设置好新外观，
		// 最好把设置外观的代码写在静态块中，
		// 并且把这个静态块写在类定义的最前面。
		FlatLightLaf.setup();
		// 主题的切换
		try {
			UIManager.setLookAndFeel(new FlatLightLaf());
		} catch (Exception ex) {
			System.err.println("Failed to initialize LaF");
		}
	}

	// UI设计
	// public void main(String[] args) {
	// // 创建SimpleWindow对象并运行
	// main window = new main();
	// window.setVisible(true);
	// }

	public main(UserInfo user, PermissInfo user_permiss) {
		System.out.println("登录账户:" + user.getAccount() + "名称:" + user.getName() + "\t特权:" + user.getKey()+"\t存储:"+user.getStorage()+"MB");
		System.out.println("权限:" + user_permiss.toString());
		setTitle(user.getSign());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 996, 625);

		getContentPane().setLayout(null);

		JPanel panel_1 = new JPanel();
		panel_1.setBackground(SystemColor.scrollbar);
		panel_1.setForeground(Color.ORANGE);
		panel_1.setBounds(95, 49, 888, 530);
		getContentPane().add(panel_1);
		panel_1.setLayout(cardLayout);

		// 默认展示
		try {
			files = service.getFiles("", user.getId(), "默认");
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (!files.isEmpty()) {
			ListShow query = new ListShow(files, "我的文件", user_permiss, user);
			// 添加查询面板
			query.setBounds(0, 0, 888, 530);
			panel_1.add(query, "query");
			cardLayout.show(panel_1, "files_default");
		} else {
			ListShow query = new ListShow(false, "你还没有文件呢╰（‵□′）╯");
			// 添加查询空面板
			query.setBounds(0, 0, 888, 530);
			panel_1.add(query, "query");
			cardLayout.show(panel_1, "files_default");
		}

		// 备份面板引入
		backup backup = new backup();
		backup.setBounds(0, 0, 888, 530);
		panel_1.add(backup, "backup");

		// 设置面板
		setting setting = new setting(user, user_permiss.getWrite());
		setting.setBounds(0, 0, 888, 530);
		panel_1.add(setting, "setting");

		// 面板搭建
		Panel panel = new Panel();
		panel.setBounds(6, 10, 83, 83);
		getContentPane().add(panel);

		// 首页logo/value.getPath()
		JLabel lblNewLabel = new JLabel("");
		if (!user.getImg().equals("https://pic.imgdb.cn/item/654dbe5ac458853aef3328a9.png")) {
			// 头像无更改，使用默认减少网络请求，因为是同步请求，会阻塞进程
			try {
				URL url = new URL(user.getImg());
				BufferedImage img = ImageIO.read(url);
				Image scaledImg = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
				ImageIcon icon = new ImageIcon(scaledImg);
				lblNewLabel.setIcon(icon);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			image = new ImageIcon("src/main/resources/images/logo.png");
			Image img = image.getImage();
			img = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
			image.setImage(img);
			lblNewLabel.setIcon(image);
		}
		panel.add(lblNewLabel);

		// 首页列表文件图标
		Panel panel_2 = new Panel();
		panel_2.setBounds(6, 100, 83, 83);
		getContentPane().add(panel_2);

		JLabel lblNewLabel_1 = new JLabel("");
		lblNewLabel_1.setVerticalAlignment(SwingConstants.BOTTOM);
		lblNewLabel_1.setIcon(new ImageIcon("src/main/resources/images/list-file.png"));
		panel_2.add(lblNewLabel_1);

		JLabel lblNewLabel_2 = new JLabel("文件");
		lblNewLabel_2.setFont(new Font("Alimama ShuHeiTi", Font.PLAIN, 15));
		panel_2.add(lblNewLabel_2);
		// 任务
		Panel panel_2_1 = new Panel();
		panel_2_1.setBounds(6, 199, 83, 83);
		getContentPane().add(panel_2_1);

		JLabel lblNewLabel_1_1 = new JLabel("");
		lblNewLabel_1_1.setIcon(new ImageIcon("src/main/resources/images/list-task.png"));
		lblNewLabel_1_1.setVerticalAlignment(SwingConstants.BOTTOM);
		panel_2_1.add(lblNewLabel_1_1);

		JLabel lblNewLabel_2_1 = new JLabel("任务");
		lblNewLabel_2_1.setFont(new Font("Alimama ShuHeiTi", Font.PLAIN, 15));
		panel_2_1.add(lblNewLabel_2_1);
		// 备份
		Panel panel_2_1_1 = new Panel();
		panel_2_1_1.setBounds(6, 299, 83, 83);
		getContentPane().add(panel_2_1_1);

		JLabel lblNewLabel_1_1_1 = new JLabel("");
		lblNewLabel_1_1_1.setIcon(new ImageIcon("src/main/resources/images/list-back.png"));
		lblNewLabel_1_1_1.setVerticalAlignment(SwingConstants.BOTTOM);
		panel_2_1_1.add(lblNewLabel_1_1_1);

		JLabel lblNewLabel_2_1_1 = new JLabel("在线");
		lblNewLabel_2_1_1.setFont(new Font("Alimama ShuHeiTi", Font.PLAIN, 15));
		panel_2_1_1.add(lblNewLabel_2_1_1);
		// 名字
		Panel panel_2_1_1_1 = new Panel();
		panel_2_1_1_1.setBounds(6, 510, 83, 58);
		getContentPane().add(panel_2_1_1_1);
		panel_2_1_1_1.setLayout(null);

		JLabel lblNewLabel_4 = new JLabel(user.getName());
		lblNewLabel_4.setHorizontalAlignment(SwingConstants.CENTER);
		lblNewLabel_4.setBounds(2, 5, 79, 19);
		lblNewLabel_4.setFont(new Font("Alimama ShuHeiTi", Font.PLAIN, 15));
		panel_2_1_1_1.add(lblNewLabel_4);

		JButton btnNewButton_2 = new JButton("");
		btnNewButton_2.setBounds(12, 29, 57, 29);
		btnNewButton_2.setIcon(new ImageIcon("src/main/resources/images/set.png"));
		panel_2_1_1_1.add(btnNewButton_2);
		// 搜索框背景
		Panel panel_3 = new Panel();
		panel_3.setBounds(681, 10, 287, 33);
		panel_3.setBackground(new Color(204, 204, 214));
		getContentPane().add(panel_3);
		panel_3.setLayout(null);

		JLabel lblNewLabel_3 = new JLabel("");
		lblNewLabel_3.setIcon(new ImageIcon("src/main/resources/images/search.png"));
		lblNewLabel_3.setBounds(6, 5, 23, 24);
		panel_3.add(lblNewLabel_3);
		// 搜索框
		textField = new JTextField();
		textField.setBounds(28, 5, 245, 24);
		panel_3.add(textField);
		textField.setColumns(10);
		// 分类按钮
		JButton btnNewButton = new JButton("默认排序");
		btnNewButton.setBounds(100, 16, 113, 27);
		getContentPane().add(btnNewButton);

		JButton btnNewButton_1 = new JButton("分类查看");
		btnNewButton_1.setBounds(227, 16, 113, 27);
		getContentPane().add(btnNewButton_1);

		JButton btnNewButton_1_1 = new JButton("上传文件");
		btnNewButton_1_1.setIcon(new ImageIcon("src\\main\\resources\\images\\upload.png"));
		btnNewButton_1_1.setBounds(354, 16, 144, 27);
		getContentPane().add(btnNewButton_1_1);
		// 事件处理
		// 分类查看
		btnNewButton_1.addActionListener(e -> {
			JPopupMenu popupMenu = new JPopupMenu();
			JMenuItem Mydocument = new JMenuItem("我的文档");
			Mydocument.setIcon(new ImageIcon("src/main/resources/images/detail.png"));
			Mydocument.addActionListener(e1 -> {
				// 我的文档
				try {
					files = service.getFiles("", user.getId(), "document");
				} catch (SQLException e11) {
					// TODO Auto-generated catch block
					e11.printStackTrace();
				}
				if (!files.isEmpty()) {
					ListShow query = new ListShow(files, "我的文档", user_permiss, user);
					// 添加查询面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				} else {
					ListShow query = new ListShow(false, "你还没有文档呢╰（‵□′）╯");
					// 添加查询空面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				}
			});
			JMenuItem Myphoto = new JMenuItem("我的相册");
			Myphoto.setIcon(new ImageIcon("src/main/resources/images/photosmall.png"));
			Myphoto.addActionListener(e1 -> {
				// 我的相册
				try {
					files = service.getFiles("", user.getId(), "photo");
				} catch (SQLException e11) {
					// TODO Auto-generated catch block
					e11.printStackTrace();
				}
				if (!files.isEmpty()) {
					ListShow query = new ListShow(files, "我的相册", user_permiss, user);
					// 添加查询面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				} else {
					ListShow query = new ListShow(false, "你还没有图片呢╰（‵□′）╯");
					// 添加查询空面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				}
			});
			JMenuItem Mymusic = new JMenuItem("我的音乐");
			Mymusic.setIcon(new ImageIcon("src/main/resources/images/music.png"));
			Mymusic.addActionListener(e1 -> {
				// 我的音乐
				try {
					files = service.getFiles("", user.getId(), "audio");
				} catch (SQLException e11) {
					// TODO Auto-generated catch block
					e11.printStackTrace();
				}
				if (!files.isEmpty()) {
					ListShow query = new ListShow(files, "我的音乐", user_permiss, user);
					// 添加查询面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				} else {
					ListShow query = new ListShow(false, "你还没有音乐呢╰（‵□′）╯");
					// 添加查询空面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				}
			});
			JMenuItem Myshare = new JMenuItem("我的分享");
			Myshare.setIcon(new ImageIcon("src/main/resources/images/share.png"));
			Myshare.addActionListener(e1 -> {
				// 我的分享
				try {
					files = service.getFiles("", user.getId(), "分享");
				} catch (SQLException e11) {
					// TODO Auto-generated catch block
					e11.printStackTrace();
				}
				if (!files.isEmpty()) {
					ListShow query = new ListShow(files, "我的分享", user_permiss, user);
					// 添加查询面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				} else {
					ListShow query = new ListShow(false, "你还没有分享过任何东西呢╰（‵□′）╯");
					// 添加查询空面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				}
			});
			JMenuItem Myother = new JMenuItem("其他文件");
			Myother.setIcon(new ImageIcon("src/main/resources/images/other.png"));
			Myother.addActionListener(e1 -> {
				// 其他
				try {
					files = service.getFiles("", user.getId(), "其他");
				} catch (SQLException e11) {
					// TODO Auto-generated catch block
					e11.printStackTrace();
				}
				if (!files.isEmpty()) {
					ListShow query = new ListShow(files, "其他文件", user_permiss, user);
					// 添加查询面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				} else {
					ListShow query = new ListShow(false, "你还没有其他文件呢╰（‵□′）╯");
					// 添加查询空面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				}
			});
			popupMenu.add(Mydocument);
			popupMenu.add(Mymusic);
			popupMenu.add(Myphoto);
			popupMenu.add(Myshare);
			popupMenu.add(Myother);
			popupMenu.show(btnNewButton_1, btnNewButton_1.getWidth() / 2, btnNewButton_1.getHeight() / 2);
		});
		// 默认排序
		btnNewButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// 调用查询
				try {
					files = service.getFiles("", user.getId(), "默认");
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if (!files.isEmpty()) {
					ListShow query = new ListShow(files, "我的文件", user_permiss, user);
					// 添加查询面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				} else {
					ListShow query = new ListShow(false, "你还没有文件呢╰（‵□′）╯");
					// 添加查询空面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				}
			}
		});
		// 鼠标移入事件
		panel_2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				// 改变背景色
				panel_2.setBackground(new Color(204, 204, 214));
				// 更改图片
				lblNewLabel_1.setIcon(new ImageIcon("src/main/resources/images/list-file-c.png"));
			}
		});
		// 添加鼠标移出事件处理器
		panel_2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseExited(MouseEvent e) {
				panel_2.setBackground(null); // 恢复背景色
				lblNewLabel_1.setIcon(new ImageIcon("src/main/resources/images/list-file.png")); // 恢复图片
			}
		});
		// 任务的事件
		panel_2_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				// 改变背景色
				panel_2_1.setBackground(new Color(204, 204, 214));
				// 更改图片
				lblNewLabel_1_1.setIcon(new ImageIcon("src/main/resources/images/list-task-c.png"));
			}
		});
		// 添加鼠标移出事件处理器
		panel_2_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseExited(MouseEvent e) {
				panel_2_1.setBackground(null); // 恢复背景色
				lblNewLabel_1_1.setIcon(new ImageIcon("src/main/resources/images/list-task.png")); // 恢复图片
			}
		});
		// 备份的鼠标事件
		panel_2_1_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				// 改变背景色
				panel_2_1_1.setBackground(new Color(204, 204, 214));
				// 更改图片
				lblNewLabel_1_1_1.setIcon(new ImageIcon("src/main/resources/images/list-back-c.png"));
			}
		});
		// 添加鼠标移出事件处理器
		panel_2_1_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseExited(MouseEvent e) {
				panel_2_1_1.setBackground(null); // 恢复背景色
				lblNewLabel_1_1_1.setIcon(new ImageIcon("src/main/resources/images/list-back.png")); // 恢复图片
			}
		});
		// 文件的点击事件
		panel_2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				try {
					files = service.getFiles("", user.getId(), "默认");
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if (!files.isEmpty()) {
					ListShow query = new ListShow(files, "我的文件", user_permiss, user);
					// 添加查询面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				} else {
					ListShow query = new ListShow(false, "你还没有文件呢╰（‵□′）╯");
					// 添加查询空面板
					query.setBounds(0, 0, 888, 530);
					panel_1.add(query, "files_default");
					cardLayout.show(panel_1, "files_default");
				}
			}
		});
		// 任务的点击事件
		panel_2_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// List<UploadInfo> files = new ArrayList<>();
				// UploadInfo file_up=new UploadInfo("花","photo",2.2,1.2);
				// files.add(file_up);
				if (!files_upload.isEmpty()) {
					routine task = new routine(files_upload);
					task.setBounds(0, 0, 888, 530);
					panel_1.add(task, "task");
				} else {
					routine task = new routine();
					task.setBounds(0, 0, 888, 530);
					panel_1.add(task, "task");
				}
				cardLayout.show(panel_1, "task");
			}
		});
		// 备份点击事件
		panel_2_1_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				cardLayout.show(panel_1, "backup");
			}
		});
		// 设置按钮
		btnNewButton_2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				cardLayout.show(panel_1, "setting");
			}
		});
		// 回车事件
		// 添加回车事件监听器
		textField.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// 获取文本框的值
				String text = textField.getText();
				// 调用方法，传入文本框值
				funtion display = new funtion();
				List<FileInfo> files;
				try {
					if (text != null && !text.isEmpty() && !text.equals("")) {
						// 调用查询
						files = service.getFiles(text, user.getId(), "查询");
						if (!files.isEmpty()) {
							ListShow query = new ListShow(files, "查询:" + text, user_permiss, user);
							// 添加查询面板
							query.setBounds(0, 0, 888, 530);
							panel_1.add(query, "query");
							cardLayout.show(panel_1, "query");
						} else {
							ListShow query = new ListShow(false, "未查询到文件");
							// 添加查询空面板
							query.setBounds(0, 0, 888, 530);
							panel_1.add(query, "query");
							cardLayout.show(panel_1, "query");
						}
					} else {
						display.tips("提示", "查询内容不能为空.");
					}
					// listfile.updateFiles(files);
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}

		});
		// 上传逻辑
		btnNewButton_1_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (user_permiss.getUpload() == 1) {
					// 创建一个新的文件选择器
					JFileChooser fileChooser = new JFileChooser();

					// 显示文件选择器对话框
					int returnValue = fileChooser.showOpenDialog(null);

					// 如果用户选择了一个文件
					if (returnValue == JFileChooser.APPROVE_OPTION) {
						// 获取用户选择的文件的绝对路径
						String filePath = fileChooser.getSelectedFile().getAbsolutePath();

						UI tip = new UI();
						upload_download upload = new upload_download();
						// 确定文件类型
						String type = null;
				        List<String> photoList = Arrays.asList("png", "jpg", "jpeg", "gif", "bmp", "webp");
				        List<String> documentList = Arrays.asList("doc", "docx", "xls", "xlsx", "pdf", "txt","ppt","pptx","md");
				        List<String> audioList = Arrays.asList("wav", "aac", "mp3", "flac", "wma");
				        if(funtion.isValidFileExtension(filePath, photoList)){
				        	type = "photo";
				        }else if (funtion.isValidFileExtension(filePath, documentList)){
				        	type = "document";
						}else if (funtion.isValidFileExtension(filePath, audioList)){
				        	type = "audio";
						}else {
							// 其他
							type = "files";
						}
						// 实例
				        System.out.println("上传文件:"+filePath+"\t类型:"+type);
						// 为文件上传模块传入参数，使用异步传输，不阻塞主线程
						Future<Boolean> future = upload_download.uploadAsync(filePath,
								new UserInfo(user.getAccount(), user.getPassword()), type);
						new Thread(() -> {
							try {
								if (future.get()) {
									tip.tips("上传", "上传成功！");
								} else {
									tip.tips("上传", "上传失败！");
								}
							} catch (Exception e1) {
								e1.printStackTrace();
							}
						}).start();

					}
				} else {
					funtion fun = new funtion();
					fun.tips("上传权限", "你无权限上传!");
				}
			}
		});
		// 分类显示，显示默认
	}
}
